import CONFIG from '@/config'
import { removeToken, setToken} from "@/utils/auth";
import request from "@/utils/request_ry";
import upload from "@/utils/upload";

let isRefreshing = false // 是否正在刷新 Token
let requestsQueue = [] // 请求队列

// 处理 401 未授权
export const handleUnauthorized = async (config, resolve, reject) => {
    if (!isRefreshing) {
        isRefreshing = true

        try {
            // 刷新 Token
            const newToken = await refreshToken()
            setToken(newToken)
            // 重发队列中的请求
            requestsQueue.forEach(cb => cb(newToken))
            requestsQueue = []

            // 重发当前请求
            config.header.token = `${newToken}`
            const res = await retryRequest(config)
            resolve(res)
        } catch (error) {
            removeToken()
            // 刷新失败跳转登录
            requestsQueue = []
            uni.reLaunch({ url: '/pages/login/index' })
            reject(error)
        } finally {
            isRefreshing = false
        }
    } else {
        // 将请求加入队列等待刷新完成
        requestsQueue.push((newToken) => {
            config.header.Authorization = `${newToken}`
            retryRequest(config).then(resolve).catch(reject)
        })
    }
}

// 刷新 Token 方法
export const refreshToken = () => {
    if(!uni.getStorageSync('zhanghao')){
        uni.clearStorageSync()
        uni.showToast({
            title: '请登录',
            icon: 'none'
        })
        setTimeout(() => {
            uni.reLaunch({ url: '/pages/login/index' })
        }, 1000)
        return;
    }

    return new Promise((resolve, reject) => {
        uni.request({
            url: CONFIG.baseUrl + '/exam/api/sys/user/login',
            method: 'POST',
            data: uni.getStorageSync('zhanghao'),
            success: (res) => {
                if (res.statusCode === 200) {
                    resolve(res.data.data.token)
                } else {
                    reject(new Error('刷新 Token 失败'))
                }
            },
            fail: reject
        })
    })
}

// 重试请求
export const retryRequest = (config) => {
    console.log(config.apiType)
    if(config.apiType === 'upload'){
        return upload(config)
    }else{
        // 解决 参数重复问题
        config.url = config.url.split('?')[0]
        return request(config)
    }
}

